<template>
  <div class="content-box pb-10 box-border">
    <TableContainer :is-page="true" :page-info="pageInfo" @current-change="handleCurrentChange" @size-change="handleSizeChange">
      <template #searchCard>
        <search-from :search-event="handleSearchEvent" />
      </template>
      <el-table
        v-bind="$attrs"
        :data="tableData"
        row-key="id"
        :height="gridOptions.height"
        :show-overflow-tooltip="gridOptions.showOverflow"
      >
        <template #empty>
          <span>暂无数据</span>
        </template>
        <el-table-column
          v-for="item in gridOptions.columns"
          :type="item.type ? item.type : 'default'"
          v-bind="{ ...item, ...$attrs }"
          :key="item.prop"
        >
          <template #default="{ row }">
            <el-tag type="primary" v-if="item.slots === 'status'">{{ FROZEN_STATUS[row.status] }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </TableContainer>
  </div>
</template>

<script lang="ts" setup>
import SearchFrom from "@/views/admin/user/components/SearchFrom.vue";
import { Role, User } from "@/api/interface";
import { getUsersByRoleId } from "@/api/modules/user";
import { useTableConfig } from "@/hooks/useTable";
import { FROZEN_STATUS } from "@/enums";
import TableContainer from "@/components/TableContainer/index.vue";
import { TPager } from "@/typings/global";

const tableData = ref<User.IUser[]>([]);

const queryForm = ref<User.IUserParams>({});

const props = defineProps<{ role: Role.IRole }>();

const { gridOptions } = useTableConfig({
  columns: [
    { type: "selection", width: 80 },
    { prop: "username", label: "用户名" },
    { prop: "nickname", label: "姓名" },
    { prop: "email", label: "邮箱" },
    { prop: "phone", label: "手机号" },
    { prop: "status", label: "状态", slots: "status" },
    { prop: "createTime", label: "创建时间" }
  ],
  controlsWidth: 100,
  isControls: false
});

const pageInfo = reactive<TPager>({
  current: 1,
  pageSize: 10,
  total: 0
});

onMounted(() => {
  getList();
});

const handleSearchEvent = form => {
  queryForm.value = form;
  getList();
};

const getList = async () => {
  try {
    const {
      data: { records, pager }
    } = await getUsersByRoleId({
      current: pageInfo.current,
      size: pageInfo.pageSize,
      ...queryForm.value,
      roleId: props.role.id
    });
    tableData.value = records;
    pageInfo.total = pager?.total || 0;
  } catch (e) {
    console.log(e);
  }
};

const handleSizeChange = size => {
  pageInfo.pageSize = size;
  pageInfo.current = 1;
  getList();
};
const handleCurrentChange = current => {
  pageInfo.current = current;
  getList();
};
</script>

<style scoped lang="scss">
.content-box {
  height: calc(100% - 60px);
}
</style>
